import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/service/feed_service.dart';
import 'package:ride_rex/service/oss_service.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../local_data/local_data_utils.dart';
import '../../ui/common_dialogs.dart';
import 'article_post_bean.dart';

class ArticlePostLogic extends GetxController with OnceClick {
  ArticlePostLogic(this.landmarkId);

  final String? landmarkId;

  static const String keyListener = 'key_listener_medal_dialog';

  final TextEditingController metersController = TextEditingController();
  final TextEditingController timeController = TextEditingController();
  final TextEditingController titleController = TextEditingController();
  final TextEditingController ideaController = TextEditingController();
  final int ideaMaxLength = 600;

  late List<PostArticleImageBean> images = [];

  ///记录当前选中的资源
  List<AssetEntity> currentSelectedImages = [];

  final int maxShow = 3;

  bool uploadFinish = true;

  @override
  void onReady() {
    super.onReady();
    ideaController.addListener(() {
      if (!ideaController.value.isComposingRangeValid) {
        update();
      }
    });
  }

  ///选择照片
  Future chooseImage() async {
    if (Loading.predicate(() => !uploadFinish, 'Image is uploading...')) return;

    CommonPrivilegeStatus status = await CommonPrivilege.photos();
    if (!status.result) {
      CommonDialogs.twoButton(
        title: status.title,
        description: status.message,
        cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
        confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
        onConfirm: () => CommonPrivilege.openSettings(),
      );
      return;
    }

    List<AssetEntity> result = await ActionPicker.assets(selected: currentSelectedImages, maxAssets: maxShow) ?? [];
    if (result.isEmpty) return;
    currentSelectedImages = result;

    List<PostArticleImageBean> temp = [];
    for (AssetEntity assetEntity in result) {
      PostArticleImageBean? bean = checkIfExist(assetEntity);
      if (bean != null) {
        ///资源已存在 -> 从images.value中取出资源
        temp.add(bean);
      } else {
        ///资源不存在 -> 创建一个bean
        temp.add(PostArticleImageBean(
          assetEntity: assetEntity,
          progress: 0,
          uploadEnd: false,
        ));
      }
    }
    images = temp;
    update();

    /// 上传图片
    uploadFinish = false;
    for (int i = 0; i < images.length; i++) {
      await _upload(i);
    }
    uploadFinish = true;
  }

  ///上传图片
  Future _upload(int index) async {
    PostArticleImageBean temp = images[index];
    if (temp.url.notEmpty || temp.isDel) return;
    File? file = await temp.assetEntity?.file;
    if (file == null) return;
    try {
      //上传图片
      OssResultBean? ossResultBean = await OssService.uploadFile(file.path, progress: (count, total) {
        temp.progress = count * 1.0 / total;
        temp.uploadEnd = count == total;
        update();
      });
      if (ossResultBean == null) return;
      temp.setValueWithUploadBean(ossResultBean);
    } catch (e) {
      Log.log('${runtimeType.toString()} : _upload : error = $e');
      temp.uploadEnd = true;
      temp.progress = -1;
      temp.url = '';
      temp.isCompressing = false;
    }
  }

  ///检查资源是否已经被选中
  PostArticleImageBean? checkIfExist(AssetEntity assetEntity) {
    PostArticleImageBean? temp;
    for (PostArticleImageBean bean in images) {
      if (assetEntity.id.equals(bean.assetEntity?.id) && !bean.isDel) {
        temp = bean;
        break;
      }
    }
    return temp;
  }

  ///删除图片
  void deleteImage(int index) {
    if (images.length > index) {
      PostArticleImageBean bean = images[index];
      bean.isDel = true;
      images.removeWhere((element) => element.assetEntity?.id.equals(bean.assetEntity?.id) ?? false);
      currentSelectedImages.removeWhere((element) => element.id.equals(bean.assetEntity?.id));

      update();
    }
  }

  ///重新上传
  void retry(int index) async {
    if (Loading.predicate(() => !uploadFinish, 'Image is uploading...')) return;
    uploadFinish = false;
    await _upload(index);
    uploadFinish = true;
  }

  ///发布
  Future publish() async {
    if (Loading.predicate(() => currentSelectedImages.isEmpty, 'Image is required')) return;
    if (Loading.predicate(() => !uploadFinish, 'Image is uploading...')) return;
    if (Loading.predicate(() => metersController.text.empty, 'Please enter riding kilometers')) return;
    if (Loading.predicate(() => timeController.text.empty, 'Please enter riding time')) return;
    if (Loading.predicate(() => titleController.text.empty, 'Please enter your title')) return;
    if (Loading.predicate(() => ideaController.text.empty, 'Please enter your idea')) return;

    CommonOperate.hideKeyboard();
    List<String> temp = images.map((e) => e.url ?? '').toList();

    startOnce(() async {
      List<String> urlList = await FeedService.instance
          .getOssSourceList(data: temp.map((e) => {"mediaPath": e, "mediaType": "image"}).toList());
      PostArticleBean bean = PostArticleBean(
        nickName: UserService.instance.notifierOfMineInfo.value.nickname,
        avatar: UserService.instance.notifierOfMineInfo.value.avatarThumbUrl,
        userId: UserService.instance.notifierOfMineInfo.value.userId,
        title: titleController.text,
        createTime: DateTime.now().millisecondsSinceEpoch.toString(),
        kilometers: metersController.text,
        ridingTime: timeController.text,
        ideas: ideaController.text,
        cover: images.map((e) => e.url ?? '').toList(),
        localFilePath: urlList,
        recordId: const Uuid().v1(),
      );

      MyPostArticleUtils.add(bean);
      Loading.toast('Post success', closeLoading: true);
      CommonRoute.close();

      if (landmarkId.notEmpty) {
        CommonObservable().publishChange(keyListener, landmarkId);
      }
    });
  }

  @override
  void onClose() {
    metersController.dispose();
    timeController.dispose();
    ideaController.dispose();
    CommonOperate.hideKeyboard();
    super.onClose();
  }
}

class PostArticleImageBean {
  String? url;
  AssetEntity? assetEntity;
  bool? uploadEnd;
  double? progress;
  bool isDel = false;

  ///视频参数
  int? width;
  int? height;
  String? duration;
  String? thumbnail;
  String? size;

  bool isCompressing = false;

  PostArticleImageBean({
    this.url,
    this.assetEntity,
    this.progress = 0,
    this.uploadEnd = true,
    this.isDel = false,
    this.width = 0,
    this.height = 0,
    this.duration,
    this.thumbnail,
    this.size,
  });

  void setValueWithUploadBean(OssResultBean uploadBean) {
    size = uploadBean.size;
    url = uploadBean.filename;
  }
}
